package edu.aynu.controller;

import edu.aynu.core.Bankers;
import edu.aynu.core.Safety;
import edu.aynu.util.Result;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.concurrent.ConcurrentHashMap;

/**
 * company: www.abc.com
 * @Author: Administrator
 * Create Data: 2021/5/10 0010
 */
@RestController
public class BankersController {


    private ConcurrentHashMap<String, Bankers> map = new ConcurrentHashMap<>();


    /**
     * 进行贷款
     */
    @PostMapping("loan/{index}")
    public Result loan(HttpServletRequest req, @PathVariable("index") Integer index,
                       @RequestBody int[] request) {
        String ip = getIpAddress(req);
        Bankers bankers = map.get(ip);
        if (bankers == null) {
            return Result.fail("请先启动实例");
        }
        boolean loan = bankers.loan(index, request);

        if (loan) {
            return Result.success().add("bankers", bankers);
        } else {
            return Result.fail();
        }
    }

    /**
     *  启动一个默认银行家算法
     */
    @PostMapping("start/default")
    public Result startDefault(HttpServletRequest request, Bankers bankers) {
        String ip = getIpAddress(request);
        map.put(ip, bankers);
        return Result.success().add("bankers", bankers);
    }

    /**
     *  启动一个银行家算法
     */
    @PostMapping("start")
    public Result start(HttpServletRequest request,@RequestBody Bankers bankers) {
        String ip = getIpAddress(request);
        map.put(ip, bankers);
        return Result.success().add("bankers", bankers);
    }

    /**
     *  查看银行贷款状态
     */
    @GetMapping("info")
    public Result start(HttpServletRequest request) {
        String ip = getIpAddress(request);
        Bankers bankers = map.get(ip);
        if (bankers == null) {
            return Result.fail();
        }
        return Result.success().add("bankers", bankers);
    }



    @GetMapping("ping")
    public String ping() {
        return "pong";
    }

    /**
     * 从request中获取请求方IP
     * @param request
     * @return
     */
    public static String getIpAddress(HttpServletRequest request) {
        String ip = request.getRemoteAddr();
        return ip;
    }
}
